package com.zx.link.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.zx.link.entity.Link;
import com.zx.link.entity.LinkType;
import com.zx.link.linstener.SystemResources;
import com.zx.link.service.LinkService;
import com.zx.link.utils.HttpImage;
import com.zx.link.utils.LinkToHtml;
import com.zx.link.utils.LinkToTreeGrid;
import com.zx.link.utils.ResponseUtil;

@Controller
public class LinkController {
	
	private final static Logger logger = LoggerFactory.getLogger(LinkController.class);
	
	@Autowired
	private LinkService linkService;
	
	/**
	 * 1.初始化页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/link.html")
	public String html(Model model){
		try {
			List<Link> all = linkService.getAll();
			model.addAttribute("links", all);
			model.addAttribute("types", SystemResources.LINK_TYPES);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return "index3";
	}
	
	/**
	 * 2.增加link
	 * @param link
	 * @param request
	 * @return
	 */
	@RequestMapping("/insert.do")
	@ResponseBody
	public String insert(Link link, HttpServletRequest request){
		try {
			//读取图标
			MultipartHttpServletRequest req = (MultipartHttpServletRequest)request;
			MultipartFile iconFile = req.getFile("iconFile");
			if(iconFile.getSize() == 0l){//没有上传图片
				//抓取网络资源自动添加图标
				byte[] httpIcon = HttpImage.getIconByUrl(link.getUrl());
				if(httpIcon != null && httpIcon.length != 0){//获得网络资源
					link.setIcon(httpIcon);
				} else {//获得网络资源失败
					byte[] img = SystemResources.DEFAUTL_IMG_BIN;
					link.setIcon(img);
				}
			} else {//上传图片
				link.setIcon(iconFile.getBytes());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
		
		try {
			link.setIsRemove(0);
			boolean b = this.linkService.insert(link);
			if(b) {
				return "1";
			} else {
				return "2";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "2";
		}
	}
	
	/**
	 * 3.逻辑删除link
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete.do")
	@ResponseBody
	public String delete(Integer id){
		try {
			Link link = this.linkService.getById(id);
			link.setIsRemove(1);
			boolean b = this.linkService.update(link);
			if(b) {
				return "1";
			} else {
				return "0";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}
	
	/**
	 * 4.彻底删除link
	 * @param id
	 * @return
	 */
	@RequestMapping("/drop.do")
	@ResponseBody
	public String drop(Integer id){
		try {
			boolean b = this.linkService.delete(id);
			if(b) {
				return "1";
			} else {
				return "0";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}
	
	/**
	 * 5.修改
	 * @param link
	 * @return
	 */
	@RequestMapping("/update.do")
	@ResponseBody
	public String update(Link link, HttpServletRequest request){
		
		try {
			//修改图片
			MultipartHttpServletRequest req = (MultipartHttpServletRequest)request;
			MultipartFile iconFile = req.getFile("iconFile");
			if(iconFile.getSize() != 0l){
				link.setIcon(iconFile.getBytes());
			} else {
				link.setIcon(this.linkService.getIconById(link.getId()));
			}
			/*byte[] httpIcon = HttpImage.getIconByUrl(link.getUrl());
			if(httpIcon == null || httpIcon.length == 0){
				link.setIcon(SystemResources.DEFAUTL_IMG_BIN);
			} else {
				link.setIcon(httpIcon);
			}*/
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
		
		try {
			boolean b = this.linkService.update(link);
			if(b) {
				return "1";
			} else {
				return "0";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}
	
	
	/**
	 * 6.查询treegrid
	 * @param response
	 */
	@RequestMapping("/treegrid.do")
	@ResponseBody
	public void getAll(HttpServletResponse response){
		try {
			List<Link> linkList = this.linkService.getAll();
			List<LinkType> types = SystemResources.LINK_TYPES;
			//将数据转为treegrid格式的数据
			String json = LinkToTreeGrid.toJson(linkList, types);
			ResponseUtil.write(response, json);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[response 写入数据失败]");
		}
	}
	
	/**
	 * 7.查询一个
	 * @param id
	 * @return
	 */
	@RequestMapping("/getById.do")
	@ResponseBody
	public Link getById(Integer id){
		try {
			return this.linkService.getById(id);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 8.查询所有类型
	 * @return
	 */
	@RequestMapping("/types.do")
	@ResponseBody
	public List<LinkType> linkType(){
		try {
			return SystemResources.LINK_TYPES;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 9.查询图片
	 * @param id
	 * @param response
	 */
	@RequestMapping("/icon/{id}.do")
	public void getIconById(@PathVariable("id") Integer id, HttpServletResponse response){
		try {
			byte[] b = linkService.getIconById(id);
			if(b != null)
				response.getOutputStream().write(b);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 10.查询回收站
	 * @param
	 * @param response
	 */
	@RequestMapping("/recycle.do")
	@ResponseBody
	public List<Link> recycle(){
		try {
			List<Link> allDelete = this.linkService.getAllDelete();
			return allDelete;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 11.恢复被删除的
	 * @param
	 * @param response
	 */
	@RequestMapping("/recover.do")
	@ResponseBody
	public String recover(Integer id){
		try {
			Link link = this.linkService.getById(id);
			link.setIsRemove(0);
			boolean b = this.linkService.update(link);
			if(b){
				return "1";
			} else {
				return "0";	
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}
	
	/**
	 * 导出书签
	 * @param response
	 */
	@RequestMapping("/bookmark.html")
	@ResponseBody()
	public void bookmark(HttpServletResponse response) {
		try {
			List<Link> linkList = this.linkService.getAll();
			List<LinkType> types = SystemResources.LINK_TYPES;
			String html = LinkToHtml.toHTML(linkList, types);
			
			response.setContentType("Content-Type:text/html;charset=UTF-8");
			response.getOutputStream().write(html.getBytes("UTF-8"));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
